﻿<%@ WebHandler Language="VB" Class="GetSong" %>

Imports System
Imports System.Web
Imports System.IO
Imports JPC.Medialibrary.UI
Imports JPC.Medialibrary.BLL
Imports JPC.Medialibrary.DAL

Public Class GetSong : Implements IHttpHandler
    Private Request As HttpRequest = Nothing
    Private Response As HttpResponse = Nothing
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Me.Request = context.Request
        Me.Response = context.Response

        Dim _songId As String = Me.Request.QueryString(0)
        
        Dim songFileInfo As FileInfo
        If MySession.SelectedSong Is Nothing Then
            songFileInfo = New FileInfo(GetSongFileName(_songId))
        Else
            If MySession.SelectedSong.SongId <> _songId Then
                songFileInfo = New FileInfo(GetSongFileName(_songId))
            Else
                songFileInfo = New FileInfo(MySession.SelectedSong.FileName)
            End If
        End If
        
        If Not songFileInfo.Exists Then
            Me.Response.StatusCode = 404
            Me.Response.ContentType = "text/html"
            Me.Response.Write(String.Format("Song file ""{0}"" was not found.", songFileInfo.FullName))
            Return
        End If

        'If UtilityMethods.Returned304(songFileInfo) Then
        '    Return
        'End If
       
        ' Serve the file:
        ' 1) Set headers
        Me.Response.Buffer = False
        Me.Response.ContentType = "audio/mpeg3"
        ' audio/wav, audio/x-ms-wma
        Me.Response.AddHeader("Content-Disposition", "filename=" + songFileInfo.Name)
       
        'No Cache
        Me.Response.Cache.SetCacheability(HttpCacheability.NoCache)

        'Me.Response.Cache.SetCacheability(HttpCacheability.[Public])
        'Me.Response.Cache.SetLastModified(songFileInfo.LastWriteTime)
        'Me.Response.Expires = 60 * 24 * 30
        ' 30 days expressed in minutes
        'Me.Response.Cache.SetSlidingExpiration(True)
       
        ' 2) Send the bits.
        Dim buffer As Byte() = New Byte(8 * 1024 - 1) {}
        Using songInStream As FileStream = songFileInfo.OpenRead()
            Dim read As Integer
            Do While True
                read = songInStream.Read(buffer, 0, buffer.Length)
                If read = 0 Then Exit Do
                Me.Response.OutputStream.Write(buffer, 0, read)
            Loop
        End Using
        
    End Sub

    Private Function GetSongFileName(ByVal _songId As String) As String
        Dim _song As New Song
        _song.LoadByKey(_songId)
        _song.IncrementPlayCount()
        Return _song.FileName
    End Function
    
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class